﻿using Enums;
using System.ComponentModel;
using System.Reflection;

namespace Untils
{
    public class ApiResponseHelper
    {
        /// <summary>
        /// 返回成功报文
        /// </summary>
        /// <param name="message">报文返回信息</param>
        /// <param name="body">报文结果</param>
        /// <returns>结果报文</returns>
        public static R SucessMessage<T, R>(string message, T? body)
        {
            var resultObj = new
            {
                Code = SystemCode.SUCCESS,
                Msg = message,
                Body = body
            };
            R result = DataConvertHelper.ConvertObject<R>(resultObj);
            return result;
        }

        /// <summary>
        /// 自定义错误码返回信息
        /// </summary>
        /// <param name="systemCode">错误码</param>
        /// <param name="message">错误信息</param>
        /// <param name="body">返回信息</param>
        /// <returns></returns>
        public static R ErrorMessage<T, R>(string systemCode, string message, T? body)
        {
            var resultObj = new
            {
                Code = systemCode,
                Msg = message,
                Body = body
            };
            R result = DataConvertHelper.ConvertObject<R>(resultObj);
            return result;
        }

        /// <summary>
        /// 获取返回码属性说明(SystemCode)
        /// </summary>
        /// <param name="en">枚举</param>
        /// <returns>返回枚举说明</returns>
        public static string GetDescription(string code, string[] parameterArrays = null)
        {
            Type type = typeof(SystemCode);
            FieldInfo[] fieldInfos = type.GetFields(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
            string value = (from field in fieldInfos where field.GetValue(null).ToString() == code select ((DescriptionAttribute)field.GetCustomAttributes(typeof(DescriptionAttribute), false)[0]).Description).First();
            return FormatDescription(code, parameterArrays, value);
        }

        public static string FormatDescription(string code, string[] parameterArrays, string value)
        {
            if (string.IsNullOrEmpty(value))
            {
                return code;
            }

            if (null == parameterArrays || 0 == parameterArrays.Length)
            {
                return value;
            }

            return string.Format(value, parameterArrays);
        }
    }
}
